<template>
  <div>
    <!-- 主屏幕 -->
    <div class="container">
      <!-- 网格概况 -->
      <div class="net">
        <div v-for="(data, index) in netList" :key="index">
          <img :src="require('@/assets/pic2/' + data.key + '.png')" alt="" />
          <p class="key">{{ data.key }}</p>
          <p class="value">{{ data.value }}</p>
        </div>
      </div>
      <!-- 网格管理员 -->
      <div class="netAdmin">
        <!-- 网格员 -->
        <div class="netMan">
          <div class="title1">
            <span>网格员</span>
          </div>
          <div v-for="(data, index) in netMan" :key="index">
            <div class="imgContainer">
              <img :src="require('@/assets/pic2/' + data.sex + '.png')" />
            </div>
            <span class="name">{{ data.name }}</span>
            <span class="phone">{{ data.phone }}</span>
            <p class="zone">
              <span style="font-weight: bold">人员年龄:</span>{{ data.age }}岁
            </p>
            <p class="zone">
              <span style="font-weight: bold">管理网格:</span>{{ data.net }}
            </p>
            <p class="zone">
              <span style="font-weight: bold">负责区域:</span>{{ data.zone }}
            </p>
          </div>
        </div>
        <!-- 党员志愿者 -->
        <div class="dangyuan">
          <div class="title1">
            <span>党员志愿者</span>
          </div>
          <div
            class="dy"
            v-for="(data, index) in dangyuanList"
            :key="index"
            @click="dyClick"
          >
            <img :src="require('@/assets/pic2/管理员.png')" />
            <span class="dyname">{{ data.name }}</span>
            <span class="dyphone">{{ data.phone }}</span>
          </div>
        </div>
      </div>
      <!-- 楼栋概况 -->
      <div class="buildings">
        <div class="title1">
          <span>楼栋概况</span>
        </div>
        <div
          class="building"
          v-for="(data, index) in buidlingsInNet"
          :key="index"
          @click="buildingSelect"
        >
          <img :src="require('@/assets/pic2/房屋定位.png')" />
          <span class="name">{{ data.name }}</span>
          <span class="num">{{ data.num }}</span>
          <span class="people">{{ data.people }}人</span>
        </div>
      </div>
    </div>
    <!--党员志愿者详细信息 -->
    <transition name="fade">
      <div class="dyDetail" v-show="dyDetailShow">
        <button @click="dyDetailShow = false">×</button>
        <div v-for="(data, index) in dyDetail" :key="index">
          <span>{{ data.key }}:</span>
          <span class="value">{{ data.value }}</span>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
/*eslint-disable */
import { getCurrentInstance, onMounted } from "vue-demi";
import axios from "axios";
import pubsub from "pubsub-js";
import url from "@/components/URL.json";
import buildingList from "@/json/裕兴花园房屋面.json";
import { useStore } from "vuex";
import { useRouter } from "vue-router";

export default {
  name: "netCut",
  data() {
    return {
      publicList: [],
      netList: [],
      netMan: [],
      dangyuanList: [],
      buildingList: [],
      buidlingsInNet: [],
      dyDetail: [],
      dyDetailShow: false,
    };
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const store = useStore();
    const router = useRouter();
    let subList = [];
    let peopleList = [];
    let netName = "";

    onMounted(() => {
      subList[0] = pubsub.subscribe("polygon", (n, data) => {
        netName = data.attributes.name;
        // 保存当前多边形信息
        store.commit("savePolygon", data);
        // 视角更新
        pubsub.publish("netView");
        // 读取设施信息
        getPoiLocation().then((poi) => {
          // console.log(poi);
          let poiList = [];
          poi.forEach((element) => {
            element.forEach((e) => {
              poiList.push(e);
            });
          });
          // 网格框选
          let list = poiSelection(poiList, data.geometry.rings[0]);
          // console.log(list);
          proxy.publicList = list;
          pubsub.publish("netPOI", list);
          store.commit("savePOI", list);
          // 网格概况
          getOverall(data, list.length);
          // 管理员概况
          getAdmin(data.attributes.name);
          setTimeout(() => {
            store.commit("renewBuildingsInNet", proxy.buidlingsInNet);
          }, 1000);
        });
      });
      subList[1] = pubsub.subscribe("netQuit", () => {
        pubsub.publish("deleteBufferPOI", proxy.publicList);
        pubsub.publish("hierarchyQuit", "@");
        pubsub.publish("firstPageShowChange", true);
        pubsub.publish("containerShowChange", false);
        subList.forEach((element) => {
          pubsub.unsubscribe(element);
        });
      });
    });

    //读取POI信息
    function getPoiLocation() {
      let arr = [];
      let dbNameList = ["安防科技", "基础设施", "停车场", "重点场所"];
      return new Promise((reslove) => {
        for (let i = 0; i < dbNameList.length; i++) {
          axios({
            method: "get",
            url: url.basicURL + "getFacility",
            params: { db: "3d_" + dbNameList[i] },
          }).then((res) => {
            arr.push(res.data);
            if (arr.length === 4) reslove(arr);
          });
        }
      });
    }

    // 网格线裁剪POI
    function poiSelection(poiList, rangePoints) {
      // console.log(poiList, rangePoints);
      // 四至截取
      let enterpriseList = MaxAndMin(poiList, rangePoints);
      //   射线求交
      let selection = RayIntersection(enterpriseList, rangePoints);
      return selection;
    }

    // 四至截取
    function MaxAndMin(poiList, rangePoints) {
      let enterpriseList = [];
      //  读取四至
      let lngMax = 0;
      let lngMin = 9999999999999999;
      let latMax = 0;
      let latMin = 999999999999999;
      rangePoints.forEach((point) => {
        let lng = point[0];
        let lat = point[1];
        if (lng > lngMax) lngMax = lng;
        if (lng < lngMin) lngMin = lng;
        if (lat > latMax) latMax = lat;
        if (lat < latMin) latMin = lat;
      });
      //  读取四至内的企业点
      poiList.forEach((element) => {
        let x = Number(element["84Lng"]);
        let y = Number(element["84Lat"]);
        if (x < lngMax && x > lngMin && y < latMax && y > latMin) {
          enterpriseList.push(element);
        }
      });
      return enterpriseList;
    }

    // 射线求交
    function RayIntersection(enterpriseList, rangePoints) {
      let selection = [];
      // 遍历四至截取后的企业点,记录水平交点数量
      enterpriseList.forEach((element) => {
        let count = 0;
        let points = [];
        for (let i = 0; i < rangePoints.length - 1; i++) {
          //  确认当前边界点与前一边界点y值的高低
          let latMax, latMin;
          if (rangePoints[i][0] > rangePoints[i + 1][0]) {
            latMax = rangePoints[i][0];
            latMin = rangePoints[i + 1][0];
          } else {
            latMax = rangePoints[i + 1][0];
            latMin = rangePoints[i][0];
          }
          //   若企业点y值在当前边界点y值之间,则认为是相交的
          if (
            Number(element["84Lng"]) > latMin &&
            Number(element["84Lng"]) < latMax
          ) {
            // 更新相交计数
            count++;
            // 将当前边界点与前一边界点保存
            points.push([rangePoints[i], rangePoints[i + 1]]);
          }
        }
        // 若与边界无相交则跳过此企业
        if (count != 0) {
          let right = 0;
          let left = 0;
          points.forEach((point) => {
            let x = boundaryFunction(point, Number(element["84Lat"]));
            x > Number(element["84Lng"]) ? right++ : left++;
          });
          //   console.log(right, left);
          //  奇数偶数判断,若左右皆奇数则认为在选区内
          if (right % 2 != 0 && left % 2 != 0) {
            selection.push(element);
          }
        }
      });
      return selection;
    }

    //  求算边界线函数,根据边界函数求算相交点的x值
    function boundaryFunction(boundary, y) {
      let point1 = {
        y: boundary[0][1],
        x: boundary[0][0],
      };
      let point2 = {
        y: boundary[1][1],
        x: boundary[1][0],
      };
      // console.log(point1, point2);
      let top = point2.x * (y - point1.y) + point1.x * (point2.y - y);
      let bottom = point2.y - point1.y;
      let x = top / bottom;
      return x;
    }

    // 网格概况信息收集
    function getOverall(net, POI) {
      let netName = net.attributes.name;
      proxy.netList = [];
      proxy.netList = [
        {
          key: "网格面积",
          value: net.attributes.area + "m²",
        },
        {
          key: "设施场所",
          value: POI + "个",
        },
      ];
      // 楼栋
      let buidlingInNet = [];
      proxy.buidlingsInNet = [];
      buildingList.features.forEach((element) => {
        if (element.attributes.name === netName) {
          proxy.buidlingsInNet.push({
            name: element.attributes.XXDZ.split("南沙街")[1],
            num: element.attributes.FWBM,
          });
          buidlingInNet.push(element);
        }
      });
      proxy.netList.push({
        key: "楼栋总数",
        value: buidlingInNet.length + "栋",
      });
      store.commit("clearPeopleInNet");
      // 人口
      getPeopleByBuilding(buidlingInNet).then((data) => {
        proxy.netList.push({
          key: "人口总数",
          value: data + "人",
        });
        for (let i = 0; i < peopleList.length; i++) {
          proxy.buidlingsInNet[i].people = peopleList[i];
        }
      });
    }

    //网格人口统计
    function getPeopleByBuilding(buidlingInNet) {
      let data = 0;
      let index = 0;
      return new Promise((reslove) => {
        buidlingInNet.forEach((building) => {
          // 读取XY,截取小数点前四位
          let x =
            Number(
              building.attributes["X"].toString().split(".")[1].substr(0, 4)
            ) /
              10000 +
            Number(building.attributes["X"].toString().split(".")[0]);
          let y =
            Number(
              building.attributes["Y"].toString().split(".")[1].substr(0, 4)
            ) /
              10000 +
            Number(building.attributes["Y"].toString().split(".")[0]);
          //   发送至后端查询数据库
          peopleList = [];
          axios({
            method: "get",
            url: url.basicURL + "getPeopleByBuilding",
            params: {
              location_x: x,
              location_y: y,
            },
          }).then((res) => {
            store.commit("pushPeopleInNet", res.data);
            peopleList.push(res.data.length);
            data += Number(res.data.length);
            index++;
            if (index === buidlingInNet.length) {
              reslove(data);
            }
          });
        });
      });
    }

    // 管理员信息读取
    function getAdmin(netName) {
      // 读取管理员信息
      axios({
        method: "get",
        url: url.basicURL + "getAdminByNet",
        params: { net: netName },
      }).then((res) => {
        proxy.netMan = [];
        res.data.forEach((element) => {
          if (element.JG === "金洲村网格员") {
            proxy.netMan.push({
              name: element.XM,
              sex: element.XB,
              phone: element.SJHM,
              net: element.WG,
              zone: element.负责区域,
              age: element.NL,
            });
          } else {
            proxy.dangyuanList.push({
              name: element.XM,
              phone: element.SJHM,
            });
          }
        });
      });
    }

    // 党员志愿者详细信息
    function dyClick() {
      // 获取人员名称
      let name = "";
      if (Array.from(event.target.children).length != 0) {
        name = Array.from(event.target.children)[1].innerHTML;
      } else {
        name = Array.from(event.target.parentNode.children)[1].innerHTML;
      }
      // 查询详细信息
      axios({
        method: "get",
        url: url.basicURL + "dyDetail",
        params: { name: name },
      }).then((res) => {
        let keyList = [
          "姓名",
          "性别",
          "手机号码",
          "身份证",
          "年龄",
          "居住地",
          "隶属",
          "职务",
        ];
        let index = 0;
        proxy.dyDetail = [];
        for (let key in res.data[0]) {
          if (key != "WG" || key != "负责区域" || key != "工作性质") {
            proxy.dyDetail.push({
              key: keyList[index] === undefined ? key : keyList[index],
              value: res.data[0][key] === 0 ? "岁数不详" : res.data[0][key],
            });
            index++;
          }
        }
        proxy.dyDetailShow = true;
      });
    }

    //楼栋选择
    function buildingSelect() {
      // 读取楼栋码
      let name = "";
      if (Array.from(event.target.children).length != 0) {
        name = Array.from(event.target.children)[2].innerHTML;
      } else {
        name = Array.from(event.target.parentNode.children)[2].innerHTML;
      }
      // 获取具体楼栋
      let b = {};
      buildingList.features.forEach((element) => {
        if (element.attributes.FWBM === name) {
          b = element;
        }
      });
      // 退出至首页
      pubsub.publish("FirstPageShow", "@");
      router.push({
        path: "/main",
      });
      pubsub.publish("needCut", true);
      pubsub.publish("needReturn", netName);
      // 跳转
      store.commit("isFromNet", true);
      setTimeout(() => {
        pubsub.publish("buildingSelected", b);
        router.push({
          path: "/buildingSelected",
        });
      }, 300);
    }

    return { dyClick, buildingSelect };
  },
  beforeRouteUpdate() {
    pubsub.publish("deleteBufferPOI", this.publicList);
    pubsub.publish("firstPageShowChange", true);
    pubsub.publish("containerShowChange", false);
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
  },
  beforeDestroy() {
    this.subList.forEach((element) => {
      pubsub.unsubscribe(element);
    });
  },
};
</script>

<style lang="less" scoped>
.container {
  height: 90%;
  width: 100%;
  background-color: rgba(6, 19, 31, 0.8);
  color: white;
}
.dyDetail {
  background-image: ~"url(@{app-images-root}/content_bg5.png)";
  background-size: 100% 100%;
  position: absolute;
  left: 38.2%;
  bottom: 92%;
  z-index: 10000;
  height: 520px;
  width: 390px;
  background-color: rgba(6, 19, 31, 0.8);
  border-radius: 7px;
  padding: 0% 0.3%;
  > button {
    float: right;
    background-color: transparent;
    color: white;
    outline: none;
    border: transparent;
    margin-right: 2%;
    margin-top: 3%;
    font-size: 120%;
  }
  > div {
    color: #f4ea2a;
    font-size: 120%;
    font-weight: bold;
    text-align: left;
    margin-top: 3%;
    margin-left: 3%;
    > .value {
      color: white;
      font-weight: normal;
      font-size: 90%;
    }
  }
}
.fade-enter-active {
  transition: all 0.3s ease-out;
}
.fade-leave-active {
  transition: all 0.3s cubic-bezier(1, 0.5, 0.3, 1);
  transform: translateY(30%);
}
.fade-enter-from,
.fade-leave-to {
  transition: 0.3s;
  transform: translateY(30%);
  opacity: 0;
}
.buildings {
  height: 95%;
  padding-right: 1%;
  position: relative;
  top: -189%;
  left: 53%;
  width: 47%;
  > .building {
    border: rgb(122, 122, 122) 1px solid;
    float: left;
    margin-left: 0.8%;
    margin-top: 0.5%;
    padding: 0.5% 1%;
    border-radius: 5px;
    > img {
      width: 30px;
    }
    > span {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    > .num {
      display: none;
    }
    > .name {
      font-size: 130%;
      font-weight: bold;
    }
    > .people {
      font-size: 115%;
      font-weight: bold;
      color: #1296db;
    }
  }
}
.building:hover {
  box-shadow: 0px 0px 5px 2px #7a7a7a;
}

.net {
  width: 18%;
  height: 95%;
  padding-right: 1%;
  position: relative;
  left: 0%;
  top: 2.5%;
  border-right: 1px solid #7a7a7a;
  > div {
    float: left;
    width: 49%;
    height: 48%;
    margin-left: 1%;
    margin-top: 1%;
    > img {
      width: 35%;
      position: relative;
      // left: -35%;
      top: 15%;
    }
    > .key {
      font-weight: bold;
      font-size: 160%;
      position: relative;
      top: 25%;
      left: 30%;
    }
    > .value {
      position: relative;
      font-weight: bold;
      font-size: 180%;
      top: -35%;
      left: 40%;
    }
  }
}
.netAdmin {
  width: 35%;
  height: 95%;
  position: relative;
  display: inline-block;
  top: -92.5%;
  left: 18%;
  border-right: 1px solid rgb(122, 122, 122);
}
.title1 {
  background-image: ~"url(@{app-images-root}/button_bg6.png)";
  background-size: 100% 100%;
  height: 30px;
  width: 300px;
  margin: 0 10px;
  > span {
    float: left;
    margin-left: 5.5%;
    font-size: 125%;
    font-weight: bold;
    color: white;
  }
}
.netMan {
  float: left;
  height: 100%;
  border-right: 1px solid rgb(122, 122, 122);
  width: 60%;
  .name {
    font-size: 150%;
    font-weight: bold;
    position: relative;
    top: -70px;
    left: 30%;
  }
  .phone {
    left: 15%;
    background-color: #1296db;
    font-size: 120%;
    font-weight: bold;
    padding: 1% 2%;
    position: relative;
    top: -30px;
    border-radius: 5px;
  }
  .zone {
    position: relative;
    top: -10px;
    text-align: left;
    left: 2.5%;
    margin-top: 4%;
    font-size: 120%;
    width: 100%;
  }
}
.imgContainer {
  box-shadow: 0px 0px 10px 2px #1296db;
  border-radius: 50%;
  width: 100px;
  height: 100px;
  position: relative;
  top: 15px;
  left: 3%;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
  > img {
    width: 87%;
  }
}
.dangyuan {
  float: left;
  height: 100%;
  width: 40%;
  > .dy {
    padding: 2%;
    text-align: left;
    padding-left: 3%;
    > img {
      width: 10%;
    }
    > .dyname {
      font-size: 150%;
      font-weight: bold;
      margin-left: 2%;
      position: relative;
      top: 5px;
    }
    > .dyphone {
      margin-left: 7px;
      position: relative;
      top: 3px;
    }
  }
}
.dy:hover {
  background-color: rgba(128, 128, 128, 0.2);
}
.dangyuan::-webkit-scrollbar {
  width: 5px;
}
.dangyuan::-webkit-scrollbar-thumb {
  height: 25px;
  border-radius: 15px;
  background: #1296db;
}
</style>